class Snake{

    //蛇头
    head:HTMLElement

    //蛇
    element:HTMLElement

    //蛇身
    body:HTMLCollection


    constructor(){
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake >div') as HTMLElement
        this.body = this.element.getElementsByTagName('div')
    }


    get X(){
        return this.head.offsetLeft
    }

    get Y(){
        return this.head.offsetTop
    }

    set X(value:number){
        //竖直移动直接return
        if(this.X == value) return

        //撞墙
        if (value>460 || value <0) throw new Error('撞墙了！彩笔！')
       
        //禁止掉头（水平）
        if (this.body[1] && (this.body[1] as HTMLElement).offsetLeft == value) {
            if(value>this.X){
              value = this.X - 10 
            }
            else{
              value = this.X + 10 
            }
          }
         
          
        this.bodymove()
        this.head.style.left = value +'px'
        this.checkheadbody()
    }

    set Y(value:number){
        //水平移动直接return
        if(this.Y == value) return

        if (value>490 || value <0) throw new Error('撞墙了！彩笔！')

        //禁止掉头（竖直）
        if (this.body[1] && (this.body[1] as HTMLElement).offsetTop == value) {
            if(value>this.Y){
              value = this.Y - 10 
            }
            else{
              value = this.Y + 10 
            }
          }

        this.bodymove()
        this.head.style.top = value + 'px'
        this.checkheadbody()
    }

    addbody(){
        let div_body = document.createElement('div')
        this.element.insertAdjacentElement('beforeend',div_body)
    }

    bodymove(){
        for(let i = this.body.length-1 ; i>0 ; i--){
            let bi = this.body[i] as HTMLElement
            let bi_1 = this.body[i-1] as HTMLElement
            bi.style.left = bi_1.offsetLeft + 'px'
            bi.style.top = bi_1.offsetTop + 'px'
        }
        
    }

    checkheadbody(){

        for(let i = this.body.length-1 ; i>0 ; i--){
            let bi = this.body[i] as HTMLElement
            if(this.X === bi.offsetLeft &&this.Y === bi.offsetTop) throw new Error('咬到自己了！萨比！')
        }
    }




}

export default Snake